<template>
	<view>
		<u-navbar :title="knowledgeBaseName" placeholder :bgColor="bgColor" :border="false" autoBack></u-navbar>
		<!-- <view class="icon-btns">
			<view class="mr-20">
				<u-icon name="search" size="24"></u-icon>
			</view>
		</view> -->
		<view class="page-wrapper">
			<scroll-view class="list-scroll" scroll-y :style="{ height: scrollHeight + 'px' }" @scrolltolower="loadMore"
				lower-threshold="50">
				<view class="select-wrap">
					<view class="title">笔记选择</view>
					<view class="options">
						<view class="op-item" v-for="item in options" :key="item.id"
							:class="{ active: item.selected === 1 }" @click="itemClick(item.id)">
							<view class="circle" :style="{ backgroundColor: item.color }"></view>
							<view class="op-name">{{ item.name }}</view>
						</view>
					</view>
					<view v-if="loading" class="loading-text">加载中...</view>
					<view v-if="noMore && options.length > 0" class="loading-text">没有更多笔记啦～</view>
					<view v-if="!loading && options.length === 0" class="loading-text">暂无笔记～</view>
				</view>
			</scroll-view>

			<view class="fixed">
				<view class="switch">
					<u-switch v-model="value" activeColor="#F16C40" />
					<view class="ml-15">随机</view>
				</view>
				<view class="start" @click="goDoExercises">开始</view>
			</view>
		</view>
	</view>
</template>

<script>
	import indexRequest from '@/api/index.js';

	export default {
		data() {
			return {
				bgColor: 'transparent',
				options: [], // 知识库笔记列表
				value: false, // 随机开关
				knowledgeBaseId: null,
				knowledgeType: null,
				knowledgeBaseName: '',
				userId: null,
				userType: null,
				page: 1,
				pageSize: 20,
				loading: false, // 加载中
				noMore: false, // 是否无更多数据
				scrollHeight: 0
			};
		},

		async onLoad(options) {
			this.knowledgeBaseId = options.knowledgeBaseId;
			this.knowledgeType = Number(options.knowledgeType);
			this.knowledgeBaseName = options.knowledgeBaseName;
			this.userId = uni.getStorageSync('userId');
			this.userType = uni.getStorageSync('bindType');

			this.calculateScrollHeight();

			await this.loadNotes(true); // 加载第一页
		},

		methods: {
			// 计算scroll-view高度（示例，可按需调整）
			calculateScrollHeight() {
				const res = uni.getSystemInfoSync();
				  // 获取导航栏高度（约44px）
				  const navBarHeight = 44;
				  // 获取底部固定区域高度（约60px）
				  const fixedBottomHeight = 60;
				  // 精确计算可用高度
				  this.scrollHeight = res.windowHeight - navBarHeight - fixedBottomHeight;
			},

			// 公共加载笔记方法，isFirstPage 标记是否是第一页加载
			async loadNotes(isFirstPage = false) {
				if (this.loading || this.noMore) return; // 防止重复加载或无更多

				this.loading = true;

				if (isFirstPage) {
					this.page = 1;
					this.noMore = false;
				}

				const queryData = {
					pageQueryDTO: {
						currentPage: this.page,
						pageSize: this.pageSize
					},
					type: uni.getStorageSync('bindType'),
					knowledgeBaseId: this.knowledgeBaseId,
					knowledgeBaseType: this.knowledgeType,
				};

				let res;
				try {
					if (this.knowledgeType === 0) {
						// 获取系统知识库id笔记列表
						res = await indexRequest.getSystemNoteListApi(queryData);
					} else {
						// 获取用户知识库id笔记列表
						res = await indexRequest.getUserNoteListApi(queryData);
					}

					const list = res?.data?.data?.content || [];

					if (isFirstPage) {
						// 首次加载直接赋值
						this.options = list.map((item, index) => ({
							id: item.id,
							name: item.name,
							color: this.getRandomHexColor(),
							selected: index === 0 ? 1 : 0
						}));
					} else {
						// 加载更多，追加数据
						const moreList = list.map((item) => ({
							id: item.id,
							name: item.name,
							color: this.getRandomHexColor(),
							selected: 0
						}));
						this.options = [...this.options, ...moreList];
					}

					// 判断是否还有更多
					if (list.length < this.pageSize) {
						this.noMore = true;
					} else {
						this.page += 1; // 有更多页，页码自增
					}
				} catch (error) {
					console.error('获取笔记列表失败:', error);
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			loadMore() {
				this.loadNotes(false);
			},

			getRandomHexColor() {
				const hex = Math.floor(Math.random() * 16777216).toString(16);
				return `#${hex.padStart(6, '0')}`;
			},

			itemClick(id) {
				this.options.forEach((item) => {
					item.selected = item.id === id ? 1 : 0;
				});
			},

			goDoExercises() {
				const selected = this.options.find((item) => item.selected === 1);
				if (!selected) {
					uni.showToast({
						title: '请先选择笔记～',
						icon: 'none'
					});
					return;
				}
				// 获取笔记类型 等同于知识库类型 这里可以直接用
				const noteType = this.knowledgeType
				uni.navigateTo({
					url: `/pages/data/drawTopicPage?noteId=${selected.id}&noteType=${noteType}`
				});
			}
		}
	};
</script>

<style lang="scss">
	
	page {
	  height: 100%;
	  overflow: hidden;
	}
	
	.page-wrapper {
	  position: relative;
	  height: 100vh;
	  box-sizing: border-box;
	  padding-bottom: 160px; /* 给底部固定区域留出空间 */
	}
	
	.list-scroll {
	  height: calc(100vh - var(--window-top) - 160px) !important;
	}
	
	.icon-btns {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding: 20rpx;
		box-sizing: border-box;

		view {
			width: 21px;
			height: 21px;
		}
	}

	.select-wrap {
		padding: 60rpx;
		font-size: 30rpx;
		color: #3d3d3d;
		padding-top: 0;


		.title {
			font-weight: 500;
			margin-bottom: 36rpx;
			margin-left: 50rpx;
		}

		.options {
			width: 100%;

			.op-item {
				width: 100%;
				height: 160rpx; /* 约80px */
				box-sizing: border-box;
				display: flex;
				align-items: center;
				padding: 26rpx;
				margin-bottom: 26rpx;
				background: #F6F4F3;
				border-radius: 45px;
				transition: all .3s;
				font-size: 30rpx;
				color: #3d3d3d;

				.circle {
					width: 62px;
					height: 62px;
					border-radius: 50%;
					margin-right: 46rpx;
				}

				.op-name {
					flex: 1;
					font-weight: 600;
				}
			}

			.op-item.active {
				border: 2rpx solid #F16C40;
				box-shadow: 0px 0px 10rpx 0px rgba(241, 108, 64, 0.6);
			}
		}
	}

	.fixed {

		padding: 0 110rpx 40rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		box-sizing: border-box;
		z-index: 9;
		background-color: #fff;
		height: 120rpx; /* 新增固定高度 */

		.switch {
			font-size: 24rpx;
			font-weight: 500;
			color: #3d3d3d;

			display: flex;
			align-items: center;
			justify-content: center;
		}

		.start {
			opacity: 1;
			font-size: 44rpx;
			font-weight: 600;
			line-height: 33px;
			letter-spacing: 0.04em;
			font-variation-settings: "opsz" auto;
			font-feature-settings: "kern" on;
			color: #000000;

			text-shadow: 0px 7px 10px rgba(153, 153, 153, 0.7);
		}
	}
</style>